<template>
  <div class="login">
    <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
      <el-form-item prop="accountNumber">
        <el-input
          placeholder="用户名"
          v-model="loginForm.accountNumber"
          clearable
          class="crrountNumber">
        </el-input>
      </el-form-item>
      <el-form-item prop="passWord">
        <el-input
        placeholder="密码"
        v-model="loginForm.passWord"
        prop="passWord"
        show-password
        class="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" class="loginBtn" @click="login('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data () {
    let passwordValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== '123') {
        callback(new Error('密码错误!'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        accountNumber: '',
        passWord: ''
      },
      rules: {
        accountNumber: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 3, message: '长度在 1 到 3 个字符', trigger: 'blur' }
        ],
        passWord: [
          // passwordValidator定义校验规则
          { validator: passwordValidator, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions('menu', [
      'getData'
    ]),
    login (formName) {
      console.log(formName)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.loginForm.accountNumber === '123' && this.loginForm.passWord === '123') {
            // 账户信息确认后，获取
            this.getData()
            this.$router.push({path: '/'})
            // 模块及菜单数据获取完成后，页面路由重定向
          } else {
            this.$refs[formName].validateField('passWord', () => {
              console.log('触发校验')
              // this.rules.passWord[0].message = '请输入正确的用户名和密码'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.login{
  width: 100%;
  padding-top: 200px;
}
.crrountNumber, .password, .loginBtn{
  width: 320px;
  margin: 0 auto;
}
</style>
